import React, { useState, useEffect, useRef } from 'react';
import { connect } from 'react-redux';
import { View, Text, Image, ScrollView } from '@tarojs/components';
import Taro from '@tarojs/taro';
import { debounce } from '@/utils/helper';
import EmptyTip from '@/components/EmptyTip';
import pRule from '@/giftCardSubPack/images/points/rule.png';
import pCash from '@/giftCardSubPack/images/points/cash.png';
import './index.scss';

const goRuleDetail = (date) => {
  let url = '/giftCardSubPack/pointsRule/index?date=' + date;
  Taro.navigateTo({ url });
};

const pageSize = 10;

const PointsPage = ({ dispatch }) => {
  const [pointsRecordList, setPointsRecordList] = useState([]);
  const [pointsInfo, setPointsInfo] = useState({});
  const [page, setPage] = useState(1);
  const recommendPage = useRef(null);
  const flags = useRef({ isLoading: false, finished: false });

  const getPointsRecord = (thepage, thepageSize) => {
    dispatch({
      type: 'otherApi/getMyPointModel',
      payload: { page: thepage, pageSize: thepageSize },
    }).then((ret) => {
      recommendPage.current = ret.pointRecordListResponses.pagination;
      if (Object.keys(pointsInfo).length === 0) {
        const {
          deductionPrice,
          exchangeRate,
          expirePoint,
          pointsValidityPeriod,
          totalPoint,
          usAblePoint,
        } = ret;
        setPointsInfo({
          deductionPrice,
          exchangeRate,
          expirePoint,
          pointsValidityPeriod,
          totalPoint,
          usAblePoint,
        });
      }
      if (thepage >= ret.pointRecordListResponses.pagination.totalPage) {
        flags.current.finished = true;
      }
      let pointsList = ret.pointRecordListResponses.list;
      if (thepage > 1) {
        pointsList = [...pointsRecordList, ...ret.pointRecordListResponses.list];
      }
      setPointsRecordList(pointsList);
      flags.current.isLoading = false;
    });
  };

  useEffect(() => {
    getPointsRecord(page, pageSize);
  }, [page]);

  const showNextDetail = debounce(() => {
    if (flags.current.finished) return;
    if (!flags.current.isLoading) {
      flags.current.isLoading = true;
      let nextPage = page + 1;
      setPage(nextPage);
    }
  }, 1200);

  return (
    <View className="totalPage_points flex-column">
      <View className="headerInfo">
        <View className="flex-row-spaceBetween white">
          <View className="flex-row--baseLine">
            <View className="num">{pointsInfo.usAblePoint || 0}</View>
            <View className="txt20">积分</View>
          </View>
          <View>
            <View
              className="flex-row--center"
              onclick={() => goRuleDetail(pointsInfo.pointsValidityPeriod)}
            >
              <View className="txt20">积分规则</View>
              <Image className="ruleIcon" src={pRule} />
            </View>
          </View>
        </View>
        <View className="txt24 pinfo pmr">
          {'已积累' +
            (pointsInfo.usAblePoint || 0) +
            '积分，消费可抵' +
            (pointsInfo.deductionPrice || 0) +
            '元'}
        </View>
        <View className="txt24 pinfo">
          {(pointsInfo.expirePoint || 0) + '个积分将在近30天失效'}
        </View>
      </View>

      <View className="contentPage flex-column--center">
        <View className="toCash flex-row">
          <View className="left">
            <View className="title">
              <Text className="t1">积分</Text>
              <Text className="t2">抵现</Text>
            </View>
            <View className="txt24">
              {'购物时' + (pointsInfo.exchangeRate || '') + '积分可以抵扣1元'}
            </View>
          </View>
          <Image className="right" src={pCash} />
        </View>

        <View className="pointDetail">
          <View className="detailLabel">积分收支明细</View>
          <ScrollView
            className="detailContent"
            scrollY
            lowerThreshold={150}
            onScrollToLower={showNextDetail}
            style={{ height: 'calc(100vh - ' + 512 + 'px)' }}
          >
            {pointsRecordList.length > 0 ? (
              pointsRecordList.map((item) => (
                <View className="oneLine flex-row-spaceBetween" key={'pointrecord_' + item.id}>
                  <View className="left">
                    <View className="txt28 mb12">{item.resourceName}</View>
                    <View className="txt24 gray">{item.created}</View>
                  </View>
                  <View className="right flex-column--end">
                    <View className="txt22 gray mb12">{'订单号' + item.orderId}</View>
                    <View className="flex-row--baseLine">
                      <Text className={'cunit' + (item.type == 2 ? ' sub' : '')}>
                        {item.type == 1 ? '+' : '-'}
                      </Text>
                      <Text className={'cnum' + (item.type == 2 ? ' sub' : '')}>{item.point}</Text>
                      <Text className="txt20">积分</Text>
                    </View>
                  </View>
                </View>
              ))
            ) : (
              <EmptyTip type="noPointRecord" className="emptyDate" />
            )}
          </ScrollView>
        </View>
      </View>
    </View>
  );
};

export default connect(() => ({}))(PointsPage);
